package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.Function;
import org.kl.bf.repository.basic.FunctionDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Qken
 * @date 2014-3-24
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class FunctionService {

	private FunctionDao functionDao;

	@Autowired
	public void setFunctionDao(FunctionDao functionDao) {
		this.functionDao = functionDao;
	}

	public Function getFunction(String guid) {
		return functionDao.findOne(guid);
	}

	public List<Function> getFunctionByMenuId(String menuId) {
		return functionDao.findByMenuId(menuId);
	};

	public void saveFunction(Function entity) {
		functionDao.save(entity);
	}

	public void deleteFunction(String guid) {
		functionDao.delete(guid);
	}

	/**
	 * 删除多条记录
	 * 
	 * @param ids
	 */
	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			System.out.println("删除记录的ID号:" + id);
			if (StringUtils.isNotBlank(id)) {
				functionDao.deleteById(id);
				i++;
			}
		}
		return "删除" + i + "条记录";
	}

	public List<Function> getAllFunction() {
		return (List<Function>) functionDao.findAll();
	}

	public List<Function> getFunctionByNoAndMenuId(String functionNo, String menuId) {
		return functionDao.findByFunctionNoAndMenuId(functionNo, menuId);
	}

	public Page<Function> getFunction(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<Function> spec = buildSpecification(searchParams);
		return functionDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Function> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<Function> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), Function.class);
		return spec;
	}

	public List<Function> getAllFunction(Map<String, Object> searchParams,String sortType, String orderType) {
		Specification<Function> spec = KLDynamicSpecifications.buildSpecification(searchParams, Function.class);
		return functionDao.findAll(spec, CRUDUtils.buildSort(sortType, orderType));
	}

}
